package com.app.controller;

import com.alibaba.fastjson.JSON;
import com.app.dao.*;
import com.app.domain.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.net.URLDecoder;
import java.util.*;

import static com.app.core.util.MyJSONUtil.addKeyValue;

@RestController
@RequestMapping("/products")
public class ProductsController {
    @Resource
    private ProductsDao productsDao;
    @Resource
    private AdminDao adminDao;
    @Resource
    private UserDao userDao;
    @Resource
    private OrderDao orderDao;

    final Integer SUPER_ADMIN = 5;


    /**
     * 管理员获取产品列表
     *
     * @param _admin 管理员
     * @return 产品列表
     */
    @PostMapping("/adminGetProducts")
    public String adminGetProducts(Admin _admin) {
        String retJSON = "[]";

        Admin admin = adminDao.getAdminByAccount(_admin.getAccount());
        List<Products> productList;

        if (admin == null) {
            return retJSON;
        }
        // 超级管理员
        if (admin.getRank() > SUPER_ADMIN) {
            productList = productsDao.getAll();
        }
        // 普通管理员
        else {
            productList = productsDao.getProductsByPublisher(admin.getAdmin_id());
        }
        retJSON = JSON.toJSONString(productList);

        return retJSON;
    }

    /**
     * 添加新产品
     *
     * @param _admin   管理员
     * @param products 新产品信息
     * @return retJSON 是否成功
     */
    @PostMapping("/addProducts")
    public String addProduct(Admin _admin, Products products) {
        String retJSON = "{}";
        Admin admin = adminDao.getAdminByAccount(_admin.getAccount());
        products.setName(URLDecoder.decode(products.getName()));
        products.setDescription(URLDecoder.decode(products.getDescription()));
        //管理员不存在
        if (admin == null) {
            retJSON = addKeyValue(retJSON, "status", "ADMIN_NOT_FOUND");
            return retJSON;
        }
        //管理员存在
        else {
            products.setPublisher(admin.getAdmin_id());
            products.setOnsale(0);
            products.setSaled(0);
            products.setGmt_create(new Date());
            products.setGmt_update(new Date());
            productsDao.insertProducts(products);
            try {
                productsDao.insertProducts(products);
                retJSON = addKeyValue(retJSON, "status", "APPROVED");
            } catch (Exception e) {
                retJSON = addKeyValue(retJSON, "status", "ALREADY_EXIST");
            }
        }
        return retJSON;
    }

    /**
     * 用户获取已上线的产品列表
     *
     * @param _user
     * @return retJSON
     */
    @PostMapping("/userGetProducts")
    public String userGetProducts(User _user) {
        String retJSON = "[]";
        User user = userDao.getUserByAccount(_user.getAccount());
        // 用户不存在
        if (user == null) {
//            retJSON = addKeyValue(retJSON , "status" , "USER_NOT_FOUND");
        } else {
            List<Products> allOnsale = productsDao.getAllOnsale();
            retJSON = JSON.toJSONString(allOnsale);
//            retJSON = addKeyValue(retJSON,"status","APPROVED");
        }

        return retJSON;
    }

    /**
     * 修改产品信息（基本信息和原子服务信息）
     *
     * @param account
     * @param _products
     * @return retJSON
     */
    @PostMapping("/updateProducts")
    public String updateProducts(String account, Products _products) {
        String retJSON = "{}";
        Admin admin = adminDao.getAdminByAccount(account);
        //不存在
        if (admin == null) {
            retJSON = addKeyValue(retJSON, "status", "ADMIN_NOT_FOUND");
            return retJSON;
        } else {
            Products products = productsDao.getProductsById(_products.getProduct_id());

            if (products == null) {
                retJSON = addKeyValue(retJSON, "status", "PRODUCT_NOT_FOUND");
                return retJSON;
            }

//            System.out.println(_product);
            //修改基本信息
            try {
                productsDao.UpdateProductsInfo(_products);
                retJSON = addKeyValue(retJSON, "status", "APPROVED");
            } catch (Exception e) {
                retJSON = addKeyValue(retJSON, "status", "ALREADY_EXIST");
            }
            return retJSON;
        }
    }

    /**
     * 删除产品
     *
     * @param _admin
     * @param _products
     * @return retJSON
     */
    @PostMapping("/deleteProduct")
    public String deleteProducts(Admin _admin, Products _products) {
        String retJSON = "{}";
        Admin admin = adminDao.getAdminByAccount(_admin.getAccount());
        //不存在
        if (admin == null) {
            retJSON = addKeyValue(retJSON, "status", "ADMIN_NOT_FOUND");
        } else {
            productsDao.DeleteById(_products.getProduct_id());
            retJSON = addKeyValue(retJSON, "status", "APPROVED");
        }
        return retJSON;
    }

    /**
     * 用户买入产品
     *
     * @param _user
     * @param _products
     * @param purchaseVolume
     * @return retJSON
     */
    @PostMapping("/purchaseProduct")
    public String purchaseProduct(User _user, Products _products, Integer purchaseVolume) {
        String retJSON = "{}";
        User user = userDao.getUserByAccount(_user.getAccount());
        Products products = productsDao.getProductsById(_products.getProduct_id());

        //用户不存在
        if (user == null) {
            retJSON = addKeyValue(retJSON, "status", "USER_NOT_FOUND");
            return retJSON;
        }
        //产品不存在或不再售卖
        if (products == null) {
            retJSON = addKeyValue(retJSON, "status", "PRODUCT_NOT_FOUND");
            return retJSON;
        }
        if (products.getOnsale() == 0) {
            retJSON = addKeyValue(retJSON, "status", "PRODUCT_NOT_ONSALE");
            return retJSON;
        }

        if (products.getPersonal_limit() < purchaseVolume) {
            //超出每人限额
            retJSON = addKeyValue(retJSON, "status", "Exceed per person limit");
        } else if (user.getBalance() < purchaseVolume) {
            //用户余额不足（不判断银行卡了，要求用户把银行卡里的钱充值到余额，只判断余额）
            retJSON = addKeyValue(retJSON, "status", "Lack_of_balance");
        } else {
            //扣款
            userDao.updateBalanceByUid(user.getUid(), user.getBalance() - purchaseVolume);

            //生成订单
            Order order = new Order(products.getProduct_id(), user.getUid(), purchaseVolume * products.getPremium(), 0, new Date(), "4321", purchaseVolume);
            orderDao.InsertOrder(order);

            //产品销量增加
            products.setSaled(products.getSaled() + purchaseVolume);
            productsDao.UpdateProductsInfo(products);
            retJSON = addKeyValue(retJSON, "status", "APPROVED");

        }
        return retJSON;
    }
}
